package com.bodystm.temperature.server;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bodystm.temperature.patient.Patient;
import com.mimosa.common.dao.HibernateDao;
import com.mimosa.common.service.CommonService;

@Service
@Transactional
public class TemperatureService extends CommonService<Temperature, String> {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Resource
	private TemperatureDao temperatureDao;

	public Temperature findLatestByEquipNoAndMeasureTime(String equipNo, Date measureTime) {
		//		Query query = this.temperatureDao.createQuery("From Temperature Where equipNo=? and measureTime> ? order by measureTime desc", equipNo, measureTime);
		Query query = this.temperatureDao.createQuery("From Temperature Where equipNo=? order by measureTime desc", equipNo);
		return (Temperature) query.setMaxResults(1).uniqueResult();
	}
	
	public List<Temperature> find24ByEquipNoAndMeasureTime(String equipNo){//, Date measureTime) {
		
		try {
			return temperatureDao.find24ByEquipNoAndMeasureTime(equipNo);//,measureTime);
//			Query query = this.temperatureDao.createQuery("From Temperature Where equipNo=? and measureTime> ? order by measureTime asc", equipNo, measureTime);
//			List<Temperature> temperatures= (List<Temperature>)query.setMaxResults(24).list();
//			return temperatures;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}

	public List<Temperature> find24ByMacsAndMeasureTime(String strMacs) {
		try {
			return temperatureDao.find24ByMacsAndMeasureTime(strMacs);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	public List<Temperature> findAllByMacs(String strMacs) {
		try {
			return temperatureDao.findAllByMacs(strMacs);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	
	/**
	 * 根据mac地址获取所有的温度数据（升序）
	 * 
	 * @param equipNo
	 * @return
	 */
	public List<Temperature> getAllByEquipNo(String equipNo) {
		try {
			// return temperatureDao.getAllByEquipNo(equipNo);
			Query query = this.temperatureDao.createQuery("From Temperature Where equipNo=? order by measureTime asc",
					equipNo);
			List<Temperature> temperatures = (List<Temperature>) query.list();
			return temperatures;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	/**
	 * 根据集中器设备号获取前一天的温度数据
	 * @param strConcentratorNo
	 * @return
	 */
	public List<Temperature> getListInOneYearByConcentratorNo(String strConcentratorNo){
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		Query query = this.temperatureDao.createQuery("From Temperature Where concentratorNo=? and measureTime> ? order by measureTime desc",strConcentratorNo, date);
 		List<Temperature> temperatures= (List<Temperature>)query.list();
 		return temperatures;
	}
	public List<Temperature> getListIn2Days(){
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		date = calendar.getTime();
		Query query = this.temperatureDao.createQuery("From Temperature Where measureTime> ? order by measureTime desc", date);
 		List<Temperature> temperatures= (List<Temperature>)query.list();
 		return temperatures;
	}

	/**
	 * 鏌ヨ浣撴俯淇℃伅
	 * 
	 * @param equipNo
	 *            璁惧鍙�
	 * @param startTime
	 *            寮�鏃舵椂
	 * @param endTime
	 *            缁撴潫鏃堕棿
	 */
	@SuppressWarnings("unchecked")
	public List<Temperature> query(final String equipNo, final Date startTime, final Date endTime, Integer rows) {
		if (rows == null) {
			rows = 20;
		}
		String sql = "FROM Temperature where equipNo=?";
		List<Object> argsList = new ArrayList<Object>();
		argsList.add(equipNo);
		if (startTime != null) {
			argsList.add(startTime);
			sql += " and measureTime>=?";
		}
		if (endTime != null) {
			Date endTimeInfo = new Date(endTime.getTime() + DateUtils.MILLIS_PER_DAY);
			argsList.add(endTimeInfo);
			sql += " and measureTime<?";
		}
		Query query = this.temperatureDao.createQuery(sql);
		int index = 0;
		for (Object obj : argsList) {
			query.setParameter(index++, obj);
		}
		query.setMaxResults(rows);
		return query.list();
	}

	/**
	 * 淇濆瓨娓╁害鏁版嵁淇℃伅
	 * 
	 * @param temperature
	 */
	public void save(Temperature temperature) {
		// 濡傛灉瀛樺湪鐩稿悓鏃堕棿鐨勮褰曪紝閭ｄ箞鎵ц鏇存柊锛屽惁鍒欐墽琛屾彃鍏ユ搷浣�
		// final String equipNo = temperature.getEquipNo();
		// final Date timeInfo = temperature.getMeasureTime();
		// Temperature resultObj =
		// this.temperatureDao.findUnique("From Temperature where equipNo=? and measureTime=?",
		// equipNo, timeInfo);
		// if (resultObj != null) {
		// String objectId = resultObj.getId();
		// BeanUtils.copyProperties(temperature, resultObj);
		// resultObj.setId(objectId);
		// } else {
		// resultObj = temperature;
		// }
		super.saveEntity(temperature);
	}
	
	public Temperature getLatestTemprature(final String equipNo){
		Query query = this.getHibernateDao().createQuery("FROM Temperature where equipNo=? order by measureTime desc", equipNo);
		Temperature temperature = (Temperature) query.setMaxResults(1).uniqueResult();
		return temperature;
	}

	public Date getLatestDate(final Patient patient, final int distance) {
		// 鏌ヨ鏈�ぇ鐨勬椂闂�
		StringBuilder maxDateSql = new StringBuilder("SELECT max(measureTime) FROM Temperature where equipNo=?");
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		if (patient.getEndTime() != null) {
			maxDateSql.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		Query query = this.temperatureDao.createQuery(maxDateSql.toString());
		int index = 0;
		for (Object obj : paramList) {
			query.setParameter(index++, obj);
		}
		Date date = (Date) query.uniqueResult();
		return date;
	}

	//static final String EXPORT_SQL = "SELECT measureNumOne,measureTime FROM T_Temperature where equipNo=? and measureTime>=DATE_SUB(?, INTERVAL ? DAY)";
	static final String EXPORT_SQL = "SELECT measureNumOne,measureTime FROM T_Temperature where equipNo=?  GROUP BY DATE_FORMAT(measureTime,'%y-%m-%d %H')";//by rxz 20160219 and measureTime>=DATE_SUB(?, INTERVAL ? DAY)

	public List<Object> getLatestRecord(final Patient patient, final Date maxMeasureDate, final int distance) {
		List<Object> list = null;
		StringBuilder queryBuilder = new StringBuilder(EXPORT_SQL);
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		//paramList.add(maxMeasureDate);
		//paramList.add(distance);
		if (patient.getEndTime() != null) {
			queryBuilder.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		SQLQuery resultQuery = this.temperatureDao.getSession().createSQLQuery(queryBuilder.toString());
		int index = 0;
		for (Object obj : paramList) {
			resultQuery.setParameter(index++, obj);
		}
		list = resultQuery.list();
		return list;
	}
	
	public List<Object> getLatestRecordByMacs(final Patient patient, final Date maxMeasureDate, final int distance,String strmacs) {
		List<Object> list = null;
		StringBuilder queryBuilder = new StringBuilder("SELECT measureNumOne,measureTime FROM T_Temperature where equipNo in ("+strmacs+") GROUP BY DATE_FORMAT(measureTime,'%y-%m-%d %H')");
		List<Object> paramList = new ArrayList<Object>();
		//paramList.add(strmacs);
		//paramList.add(maxMeasureDate);
		//paramList.add(distance);
		/*if (patient.getEndTime() != null) {
			queryBuilder.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}*/
		SQLQuery resultQuery = this.temperatureDao.getSession().createSQLQuery(queryBuilder.toString());
		int index = 0;
		for (Object obj : paramList) {
			resultQuery.setParameter(index++, obj);
		}
		list = resultQuery.list();
		return list;
	}

	public Temperature getLatestPoint(final Date lastDate, final String equipNo) {
		Query query = this.getHibernateDao().createQuery("FROM Temperature where equipNo=? and measureTime>=? order by measureTime desc", equipNo, lastDate);
		Temperature temperature = (Temperature) query.setMaxResults(1).uniqueResult();
		return temperature;
	}

	@Override
	protected HibernateDao<Temperature, String> getHibernateDao() {
		return this.temperatureDao;
	}
}